package com.aruba.lifecycle;

import android.content.Context;
import android.os.SystemClock;
import android.util.AttributeSet;
import android.widget.Chronometer;

import androidx.lifecycle.Lifecycle;
import androidx.lifecycle.LifecycleObserver;
import androidx.lifecycle.OnLifecycleEvent;

/**
 * Created by aruba on 2021/9/9.
 */
class MyChronometer extends Chronometer implements LifecycleObserver {//实现LifecycleObserver接口

    private long countTime;

    public MyChronometer(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    //对应生命周期的注解
    @OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
    private void startCount() {
        //恢复计时，基于休息的时间作一个偏移
        setBase(SystemClock.elapsedRealtime() - countTime);
        start();
    }

    //对应生命周期的注解
    @OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
    private void stopCount() {
        //记录下计时时间
        countTime = SystemClock.elapsedRealtime() - getBase();
        stop();
    }

}
